﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RAP.Framework.Libary.Utils;

namespace RAP.Web.Libary.Controller.Filters
{
  /// <summary>
  /// 
  /// </summary>
  public class JSONResultFilter : IAsyncResultFilter
  {
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
      if (context.Result is JsonResult)
      {
        var result = context.Result as JsonResult;
        var jsonContent = result.Value.ToJSON();
        var contentLength = jsonContent != null ? Encoding.UTF8.GetByteCount(jsonContent) : 0;
        var response = context.HttpContext.Response;
        response.ContentLength = contentLength;
        response.ContentType = "application/json;charset=utf-8";

        await response.WriteAsync(jsonContent ?? string.Empty);
        return;
      }
      await next();
    }
  }
}
